package com.smartwork.common.identifyCode;

import com.smartwork.common.config.Global;
import com.smartwork.common.mobile.constant.ResponseCodeConst;
import com.smartwork.common.mobile.exception.BizException;
import com.smartwork.common.sms.aliyun.AliYunUtil;
import com.smartwork.common.utils.DateUtils;
import com.smartwork.common.utils.RandUtil;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 验证码工具类
 * 
 * @author albert.ym
 * 
 */
public class IdentifyCodeUtil {

	private static ConcurrentMap<String, IdentifyCode> map = new ConcurrentHashMap<String, IdentifyCode>();

	public static synchronized void setIdentifyCode(String phoneNum) {
        String templateCode= Global.getConfig("ali_sms_identify_code");
        String signName= Global.getConfig("ali_sms_sign_name");
		String randNumber = RandUtil.getNumberRandStr(6);
		IdentifyCode code = new IdentifyCode();
		code.setCode(randNumber);
		// 设置有效期为30分钟
		code.setExpiredTime(DateUtils.addTime(new Date(), 30, Calendar.MINUTE));
		map.put(phoneNum, code);
        AliYunUtil.sendMsg(phoneNum,"{code:\""+randNumber+"\"}",templateCode,signName);
	}



	public static synchronized boolean verifySignature(String phoneNum,
			String captcha) throws BizException {
		IdentifyCode identifyCode = map.get(phoneNum);
		if (null == identifyCode) {
			throw new BizException(ResponseCodeConst.NO_DATA,
					ExceptionMessage.CAPTCHA_NULL);
		}
		// 过期
		if (identifyCode.getExpiredTime().before(new Date())) {
			throw new BizException(ResponseCodeConst.NO_DATA,
					ExceptionMessage.CAPTCHA_TIMEOUT);
		}
		if (identifyCode.getCode().equals(captcha)) {
			map.remove(phoneNum);
			return true;
		} else {
			throw new BizException(ResponseCodeConst.NO_DATA,
					ExceptionMessage.CAPTCHA_ERROR);
		}
	}

	public static class ExceptionMessage {
		public static final String CAPTCHA_TIMEOUT = "验证码过期!";
		public static final String CAPTCHA_ERROR = "验证码错误!";
		public static final String CAPTCHA_NULL = "验证码无效!";
		public static final String MOBILE_NULL = "电话号码为空!";
	}

}
